package business_opportunity

import (
	"git.mycaigou.com/gfyx/micro-gfyx-api/http_server/controller"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	dto "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/business_opportunity"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/utils"
	orderService "git.mycaigou.com/gfyx/micro-gfyx-api/service/business_opportunity/order"
	"github.com/gin-gonic/gin"
)

type OrderController struct {
	controller.BaseController
	orderService orderService.OrderServiceIface
}

// NewOrderController 订单控制器
func NewOrderController(
	orderService orderService.OrderServiceIface,
) *OrderController {
	return &OrderController{
		orderService: orderService,
	}
}

func (c *OrderController) RegisterRouter(g *gin.RouterGroup) {
	// 保存订单
	g.POST("order/save", c.save)
	// 订单预览
	g.POST("order/preview", c.preview)
	// 订单列表
	g.POST("order/list", c.list)
	// 订单详情
	g.GET("order/detail", c.detail)
}

func (c *OrderController) save(ctx *gin.Context) {
	var request dto.SaveOrderRequest
	if err := ctx.ShouldBind(&request); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils.GetValidateErr(request, err))
		return
	}
	resp, err := c.orderService.SaveOrder(ctx, &request)
	if err != nil {
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}
	if resp.IsPaid == false {
		c.FailWithData(ctx, errcode.OrderNoAvailableExportNumError, "支付失败，当前可导出条数不足，请联系客户经理充值", resp)
		return
	}
	c.Success(ctx, resp)
}

func (c *OrderController) preview(ctx *gin.Context) {
	var request dto.PreviewOrderRequest
	if err := ctx.ShouldBind(&request); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils.GetValidateErr(request, err))
		return
	}
	resp, err := c.orderService.PreviewOrder(ctx, &request)
	if err != nil {
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	c.Success(ctx, resp)
}

func (c *OrderController) list(ctx *gin.Context) {
	var request dto.GetOrderListRequest
	if err := ctx.ShouldBind(&request); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils.GetValidateErr(request, err))
		return
	}
	resp, err := c.orderService.GetOrderList(ctx, &request)
	if err != nil {
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	c.Success(ctx, resp)
}

func (c *OrderController) detail(ctx *gin.Context) {
	var request dto.GetOrderDetailRequest
	if err := ctx.ShouldBind(&request); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils.GetValidateErr(request, err))
		return
	}
	resp, err := c.orderService.GetOrderDetail(ctx, &request)
	if err != nil {
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	c.Success(ctx, resp)
}
